﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
//namespace Common.Extensions
//{
    public static class MailExtensions
    {
        public static void AddRecipients(this MailMessage mail, Dictionary<string, string> recipients, Encoding encoding = null)
        {
            foreach (var recipient in recipients)
            {
                try
                {
                    var address = recipient.Key;
                    var recipientInfo = recipients.GetKeyValuePair(recipient.Key);
                    var displayName = String.IsNullOrEmpty(recipientInfo.Value) ? String.Empty : recipientInfo.Value;
                    if ( !String.IsNullOrEmpty(address) )
                        mail.To.Add( new MailAddress(address, displayName, encoding ?? Encoding.UTF8) );    
                }
                catch (FormatException)
                {
                    //E-mail address is not provided with expected format                        
                }
            }
        }

        public static string GetRecipients(this MailMessage mail)
        {
            var recipientList = String.Empty;
            if ( mail.To.IsNotNull() )
            {
                var recipients = new string[mail.To.Count];
                for (var i = 0; i < mail.To.Count; i++)
                {
                    recipients[i] = mail.To[i].Address;
                }
                recipientList = String.Join( ",", recipients );
            }
            return recipientList;
        }
    }
//}
